package query.select

import ast.statement.select.SqlSelectQuery
import ast.statement.select.SqlUnionSelect
import ast.statement.select.SqlUnionType
import database.DBConnection
import dsl.count
import database.DB
import util.toSqlString
import java.sql.Connection

/**
 * union select语句dsl类
 * @property db DB 数据库类型
 * @property conn Connection? 数据库连接
 * @property isTransaction Boolean 是否是事务
 * @property dbConnection DBConnection? 基础查询类
 * @property unionSelect SqlUnionSelect union select语法树
 */
class UnionSelect(
    left: SelectQuery,
    operator: SqlUnionType,
    right: SelectQuery,
    var db: DB = DB.MYSQL,
    override var conn: Connection? = null,
    override var isTransaction: Boolean = false,
    override var dbConnection: DBConnection? = null
) :
    SelectQueryImpl() {
    private var unionSelect = SqlUnionSelect(left.getSelect(), operator, right.getSelect())

    init {
        this.conn = left.conn
        this.dbConnection = left.dbConnection
    }

    /**
     * 生成sql语句
     * @return String sql语句
     */
    override fun sql(): String = toSqlString(unionSelect, db)

    /**
     * 获取sql语法树
     * @return SqlSelectQuery sql语法树
     */
    override fun getSelect(): SqlSelectQuery {
        return this.unionSelect
    }

    /**
     * 获取数据库类型
     * @return DB 数据库类型
     */
    override fun getDbType(): DB {
        return this.db
    }

    /**
     * 查询总数
     * @return Long 总数
     */
    override fun fetchCount(): Long {
        val select = Select(this.db).select(count() alias "count").from(this).alias("t")
        val result = query(select.sql(), isTransaction, conn!!, dbConnection)

        return result[0]["count"] as Long
    }
}